<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>workerman-chat PHP聊天室 Websocket(HTLM5/Flash)+PHP多进程socket实时推送技术</title>
    <script type="text/javascript">
        //WebSocket = null;
    </script>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/css/style.css" rel="stylesheet">
    <!-- Include these three JS files: -->
    <script type="text/javascript" src="/static/js/swfobject.js"></script>
    <script type="text/javascript" src="/static/js/web_socket.js"></script>
    <script type="text/javascript" src="/static/js/jquery.min.js"></script>

    </head>
<body>

<div style="width:20px;height:20px;border:1px solid red;" class="ceshi"></div>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-1 column">
        </div>
        <div class="col-md-6 column">
            <div class="thumbnail">
                <div class="caption" id="dialog"></div>
            </div>
            <form onsubmit="return onSubmit();">
                <select style="margin-bottom:8px" id="client_list">
                    <option value="all">所有人</option>
                </select>
                <textarea class="textarea thumbnail" id="textarea"></textarea>
                <div class="say-btn">
                    <input type="submit" class="btn btn-default" value="发表" />
                </div>
            </form>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;<b>房间列表:</b>（当前在&nbsp;房间<?php echo isset($_GET['room_id'])&&intval($_GET['room_id'])>0 ? intval($_GET['room_id']):1; ?>）<br>
                &nbsp;&nbsp;&nbsp;&nbsp;<a href="/push/index/index/?room_id=1">房间1</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="/push/index/index/?room_id=2">房间2</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="/push/index/index/?room_id=3">房间3</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="/push/index/index/?room_id=4">房间4</a>
                <br><br>
            </div>
            <!--<p class="cp">PHP多进程+Websocket(HTML5/Flash)+PHP Socket实时推送技术&nbsp;&nbsp;&nbsp;&nbsp;Powered by <a href="http://www.workerman.net/workerman-chat" target="_blank">workerman-chat</a></p>-->
        </div>
        <div class="col-md-3 column">
            <div class="thumbnail">
                <div class="caption" id="userlist"></div>
            </div>
            <!--<a href="http://workerman.net:8383" target="_blank"><img style="width:252px;margin-left:5px;" src="/static/img/workerman-todpole.png"></a>-->
        </div>
    </div>
</div>
</body>
    <script type="text/javascript">
        if (typeof console == "undefined") { this.console = { log: function (msg) { } };}
        // 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
        WEB_SOCKET_SWF_LOCATION = "/static/swf/WebSocketMain.swf";
        // 开启flash的websocket debug
        WEB_SOCKET_DEBUG = true;

        var ws, name, client_list = {};

        connect();

        // 连接服务端
        function connect() {
// 创建websocket
            console.log(document.domain);
            //ws = new WebSocket("ws://47.104.136.152:2348");
            ws = new WebSocket("ws://"+document.domain+":2348");
//console.log(ws);
// 当socket连接打开时，输入用户名
            ws.onopen = onopen;
// 当有消息时根据消息类型显示不同信息
            ws.onmessage = onmessage;
            ws.onclose = function() {
                console.log("连接关闭，定时重连");
                connect();
            };
            ws.onerror = function() {
                console.log("出现错误");
            };
        }

        // 连接建立时发送登录信息
        function onopen()
        {
            if(!name)
            {
                show_prompt();
            }

            // 登录  公司角色  member_no = 'company1' role = 'company'  client_name = '方太' room_id = 1
            // 登录  用户角色  member_no = '170931'   role = 'user'     client_name = '若安好' room_id = 1
            var login_data = '{"type":"login","role":"<?php echo $_GET['role']?>","member_no":"<?php echo $_GET['member_no']?>","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"<?php echo isset($_GET['room_id']) ? $_GET['room_id'] : 1?>"}';

            // {"type":"login","role":"company","member_no":company1",client_name":"fangtai","room_id":"1"}

            // {"type":"login","role":"user","member_no":"170931","client_name":"若安好","room_id":"1"}

            // http://fangtai.0513app.cn/push/index?member_no=170931&role_type=user&room_id=1

            console.log("websocket握手成功，发送登录数据:"+login_data);
            ws.send(login_data);

            setInterval(show,1000);


        }

        function show()
        {
            var heartbeat = '{"type":"heartbeat","client_name":"'+name.replace(/"/g, '\\"')+'","room_ids":"<?php echo isset($_GET['room_id']) ? $_GET['room_id'] : 1?>"}';
            ws.send(heartbeat);
            console.info("向服务端发送心跳包字符串:"+heartbeat);
        }

        // 服务端发来消息时
        function onmessage(e)
        {
            console.log(e.data);
            var data = eval("("+e.data+")");

            console.log('我是'+data);
            switch (data['type']) {

                case 'send_red_envelopes':

                    // ws.send('{"type":"grab_red_envelope","live_id":"22","type":"1","member_id":"14","red_envelopes_id":"'+data['red_envelopes_id']+'"}');
                    ws.send('{"type":"grab","live_id":"22","user_type":"1","member_id":"14","red_envelopes_id":"17"}');

                    break;

                case 'grab_red_envelope':
                    alert(data['get_total']);

                    break;


                // client_id连接上的时候
                case 'init':

                    console.log('当前client_id是'+data['client_id']);

                    break;

                // 服务端ping客户端
                case 'ping':
                    // ws.send('{"type":"pong"}');
                    break;
                case 'send_to_all':
                    console.log('我是向所有人说的内容'+data);
                    break;
                // 登录 更新用户列表
                case 'login':
                //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}

                    console.log('login打印');
                    console.log(data['client_id']);
                    console.log(data['client_name']);
                    console.log(data['client_list']);

                    say(data['client_id'], data['client_name'], data['client_name']+' 加入了聊天室', data['time']);
                    if(data['client_list'])
                    {
                        client_list = data['client_list'];
                    }
                    else
                    {
                        client_list[data['client_id']] = data['client_name'];
                    }
                    flush_client_list();
                    console.log(data['client_name']+"登录成功");
                    break;
                // 发言
                case 'say':
                //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
                    say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
                    break;

                case 'heartbeat':
                    console.log(data['client_name']+"的心跳监测");
                    break;

                case 'no_say':

                    console.log('接收到no_say:'+data);
                    break;

                // 用户退出 更新用户列表
                case 'logout':
                //{"type":"logout","client_id":xxx,"time":"xxx"}

                    console.log('我是logout');

                    say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
                    delete client_list[data['from_client_id']];
                    flush_client_list();
            }
        }

        $('.ceshi').click(function(){
            send_red_envelopes();
        });

        function tijiao_no_say()
        {
            //ws.send('{"type":"no_say","room_id":"22","mobile":"15006290842","to_mobile":"15050640606"}');

            ws.send('{"type":"no_say","room_id":"22","to_member_no":"15050640606"}');

        }

        function tijiao_jiechu_no_say()
        {
            //ws.send('{"type":"jiechu_no_say","room_id":"22","mobile":"15006290842","to_mobile":"15050640606"}');
            ws.send('{"type":"jiechu_no_say","room_id":"22","to_member_no":"15050640606"}');

        }

        function lottery_start()
        {
            ws.send('{"type":"lottery_start","live_id":"25","company_id":"1","member_no":"170931"}');

        }

        function lottery_end()
        {
            ws.send('{"type":"lottery_end","live_id":"22","merchant_id":"3","mobile":"15006290842"}');

        }
        // 发红包

        function send_red_envelopes()
        {
            ws.send('{"type":"send_red_envelopes","live_id":"22","company_id":"3","total":"5","num":"2"}');

        }

        // 抢红包 Grab a red envelope
        function grab_red_envelope()
        {
            ws.send('{"type":"grab","live_id":"22","company_id":"1","user_type":"1","member_id":"3","red_envelopes_id":"1"}');
        }

        // 发优惠券
        function send_coupons()
        {
            ws.send('{"type":"send_coupons","live_id":"22","company_id":"3","coupon_id":"5"}');

        }

        // 客户端 点击 发起领取优惠券指令
        function receive_coupon()
        {
            ws.send('{"type":"receive_coupon","live_id":"22","user_type":"1","member_id":"3","coupon_id":"1"}');
        }

        // 输入姓名
        function show_prompt(){
            name = prompt('输入你的名字：', '');
            if(!name || name=='null'){
                name = '游客';
            }
        }

        // 提交对话
        function onSubmit() {
            var input = document.getElementById("textarea");
            var to_client_id = $("#client_list option:selected").attr("value");
            var to_client_name = $("#client_list option:selected").text();
            ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
            input.value = "";
            input.focus();
            return false;
        }

        // 刷新用户列表框
        function flush_client_list(){
            var userlist_window = $("#userlist");
            var client_list_slelect = $("#client_list");
            userlist_window.empty();
            client_list_slelect.empty();
            userlist_window.append('<h4>在线用户</h4><ul>');
            client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
            for(var p in client_list){
                userlist_window.append('<li id="'+p+'">'+client_list[p]+'</li>');
                client_list_slelect.append('<option value="'+p+'">'+client_list[p]+'</option>');
            }
            $("#client_list").val(select_client_id);
            userlist_window.append('</ul>');
        }

        // 发言
        function say(from_client_id, from_client_name, content, time){
            $("#dialog").append('<div class="speech_item"><img src="http://lorempixel.com/38/38/?'+from_client_id+'" class="user_icon" /> '+from_client_name+' <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>');
        }

        $(function(){
            select_client_id = 'all';
            $("#client_list").change(function(){
                select_client_id = $("#client_list option:selected").attr("value");
            });
        });
    </script>
</html>